/* $RCSFile: LeadGrid.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/LeadGrid/LeadGrid.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:21  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:55  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:25  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Diagnostics;
using System.Data.SqlClient;
using System.Web.Services.Protocols;
using System.Globalization;

using AddonNice.UI;
using AddonNice.Design;
using AddonNice.UI.WebControls;
using AddonNice.Security;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Settings;
using AddonNice.Authentication;

using AddonNice.CRMWrapper;
using AddonNice.CRMWrapper.Design;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.LeadGrid 
{

 	#region Local TraceSwitch 
	public class CrmGridTrace : ADNTraceSwitch
	{
		static public ADNTraceSwitch	Sw	            =	new ADNTraceSwitch("CrmGridTrace","Special Trace Switch for CrmGridTrace");
	}
	#endregion Local TraceSwitch 

    #region const strings
    public class LStr
    {
		public const string ClassicEntities         =	"MODULE_SETTINGS_LEAD_GRID_CLASSICENTITIES";
		public const string LeadGridEntity  	    =	"MODULE_SETTINGS_LEAD_GRID_ENTITY";
		public const string LeadGridFields  	    =	"MODULE_SETTINGS_LEAD_GRID_FIELDS";
		public const string Scroll				    =	"MODULE_SETTINGS_LEAD_GRID_SCROLLING";
		public const string PageSz				    =	"MODULE_SETTINGS_LEAD_GRID_PAGESIZE";
		public const string Paging				    =	"MODULE_SETTINGS_LEAD_GRID_PAGING";
        public const string ImpersonateUser		    =	"MODULE_SETTINGS_LEAD_GRID_IMPERSONATE_USER";
		public const string ShouldImpersonate	    =	"MODULE_SETTINGS_LEAD_GRID_SHOULD_IMPERSONATE";
		public const string DetectFormAuth	        =	"MODULE_SETTINGS_LEAD_GRID_DETECT_FORMS_AUTH";
        
        
        public const string PrimaryKeyColumn        =   "MODULE_SETTINGS_LEAD_GRID_PRIMARYKEYCOLUMN";
        public const string SpecialColumn           =   "MODULE_SETTINGS_LEAD_GRID_SPECIALCOLUMN";
        public const string WithDisplayName         =   "MODULE_SETTINGS_LEAD_GRID_WITHDISPLAYNAME";
        public const string DisplayDateOnly         =   "MODULE_SETTINGS_LEAD_GRID_DISPLAYDATESAS_DATEONLY";
        public const string DisplayTimeOnly         =   "MODULE_SETTINGS_LEAD_GRID_DISPLAYDATESAS_TIMEONLY";
        public const string FormatedAmounts         =   "MODULE_SETTINGS_LEAD_GRID_DISPLAYDFORMATED_AMOUNT";

        public const string RequiredNone            =   "MODULE_SETTINGS_LEAD_GRID_REQUIREDNONE";
		public const string ObjectTypeCode          =	"MODULE_SETTINGS_LEAD_GRID_OBJECTTYPECODE";
		public const string PrimaryName             =	"MODULE_SETTINGS_LEAD_GRID_PRIMARYNAME";
		public const string RequiredForForm         =	"MODULE_SETTINGS_LEAD_GRID_REQUIREDFORFORM";
		public const string ValidForForm            =	"MODULE_SETTINGS_LEAD_GRID_VALIDFORFORM";
		public const string RequiredForGrid         =	"MODULE_SETTINGS_LEAD_GRID_REQUIREDFORGRID";
		public const string ValidForGrid            =	"MODULE_SETTINGS_LEAD_GRID_VALIDFORGRID";
		public const string ValidForAdvancedFind    =	"MODULE_SETTINGS_LEAD_GRID_VALIDFORADVANCEDFIND";
            
		public const string IgnoreFormating         =   "MODULE_SETTINGS_LEAD_GRID_IGNORE_FORMATING";
		public const string IgnorePaging            =   "MODULE_SETTINGS_LEAD_GRID_IGNORE_PAGING";
		public const string Filter                  =   "MODULE_SETTINGS_LEAD_GRID_FILTER";
		public const string OpenInNewWindow         =   "MODULE_SETTINGS_LEAD_GRID_OPENNEWWINDOW";
		public const string AllowFilteringByColumn  =	"MODULE_SETTINGS_LEAD_ALLOW_FILTERING";
		public const string GroupingEnabled         =	"MODULE_SETTINGS_LEAD_GROUPING_ENABLED";
    }
    #endregion const strings
    
    /// <summary>
    /// Initializer class for LeadGrid 
    /// </summary>
    public class LeadGridSI : PortalCRMModuleControlSI
    {
        bool inCtor     =   true;

        ArrayList _AllEntities =   null;
        ArrayList GetAllEntities(bool useAll)
        {
            if (_AllEntities == null)
            {
                _AllEntities          =   MetadataCache.GetAllEntities(Wrapper,useAll);
            }
            return _AllEntities;
        }
        
        /// <summary>
        /// Get the Entity Config to build the attributes table
        /// </summary>
        EntityConfig _TConfig   =   null;
        string _entityName      =   string.Empty; //small caching for columns
        public EntityConfig GetEntityConfig(string entityName)
        {
            if (_TConfig == null || 
                (_TConfig.entityFlags != EntityInternalItems.All) || 
                ( !_TConfig.isAdmin ) || 
                (_entityName != entityName) )
            {
                _TConfig                    = new EntityConfig(Wrapper,entityName);
                _entityName                 = entityName;
                if ( CrmGridTrace.Sw.TraceVerbose )
                    Trace2.WriteLine(
                    string.Format("[V]LeadGrid GetEntityConfig created entityName: {0}, vflag: [{1}], isAdmin: {2}, DisplayMask: [{3}] ",
                    new object[] {entityName,_TConfig.entityFlags, true, _TConfig.DisplayMask }),CrmGridTrace.Sw.Info);
            }
            return _TConfig;
        }


        /// <summary>
        /// Called from settingsItems to handle a change in entity filter
        /// </summary>
        void HandleFilterEntity(object sender, SettingItemsEventArgs ev)
        {
            if ( CrmGridTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid HandleFilterEntity BEG sender: {0}, EventType: {1}.",((SettingItem)sender).EnglishName,ev.EventType),CrmGridTrace.Sw.Info);
            if ( ev.EventType != SettingItemsEventType.ParentLoaded &&
                    ev.EventType != SettingItemsEventType.ParentChanged )
            {
                if ( CrmGridTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid HandleFilterEntity  DISCARDED sender: {0}, EventType: {1}, (ev.dataTypeEventArg == null): {2}.", ((SettingItem)sender).EnglishName, ev.EventType,ev.dataTypeEventArg == null ),CrmGridTrace.Sw.Info);
                return;
            }
            // force reset
            _AllEntities                            =   null;
            // useless this is the caller : Settings[LStr.ClassicEntities].Value    =   useClassic.ToString();
            string selEntity                        =   CrmStr.account; // reset to default
            bool useClassic                         =   false;
            if ( !string.IsNullOrEmpty(ev.dataTypeEventArg.newVal) )
                bool.TryParse(ev.dataTypeEventArg.newVal,out useClassic);
            // should trigger HandleEntityChange
            Owner.Settings[LStr.LeadGridEntity].DataType.ResetDataSource(GetAllEntities(!useClassic),selEntity);
            if ( CrmGridTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid HandleFilterEntity END selEntity: '{0}'.",selEntity),CrmGridTrace.Sw.Info);
        }

        /// <summary>
        /// Called from settingsItems to handle a change in entity name
        /// </summary>
        void HandleEntityChange(object sender, SettingItemsEventArgs ev)
        {
            if ( CrmGridTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid HandleEntityChange BEG sender: {0}, EventType: {1}, inCtor: {2}",((SettingItem)sender).EnglishName,ev.EventType,inCtor),CrmGridTrace.Sw.Info);
            if ( ev.EventType != SettingItemsEventType.ParentLoaded 
                && ev.EventType != SettingItemsEventType.ParentChanged 
                && ev.EventType != SettingItemsEventType.ParentRebound )
            {
                if ( CrmGridTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid HandleEntityChange  DISCARDED sender: {0}, EventType: {1}, (ev.dataTypeEventArg == null): {2}.", ((SettingItem)sender).EnglishName, ev.EventType,ev.dataTypeEventArg == null ),CrmGridTrace.Sw.Info);
                return;
            }
            
            string entityName                   =   Owner.Settings[LStr.LeadGridEntity].Value;
            
            if ( CrmGridTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid HandleEntityChange entityName: '{0}'",entityName),CrmGridTrace.Sw.Info);
            DataTable tb                        =   CreateAttributesTable();
            // reset GetEntityConfig to force reading new entityname
            EntityConfig econf                  =   GetEntityConfig(entityName);
            bool filterNullDisplay              =   Owner.Settings[LStr.WithDisplayName].ToBool();
            
            InternalDisplayMasks validFlag      =   0;
            if ( Owner.Settings[LStr.RequiredNone].ToBool() )
                validFlag      |=   InternalDisplayMasks.None;
            if ( Owner.Settings[LStr.ObjectTypeCode].ToBool() )
                validFlag      |=   InternalDisplayMasks.ObjectTypeCode;
            if ( Owner.Settings[LStr.PrimaryName].ToBool() )
                validFlag      |=   InternalDisplayMasks.PrimaryName;
            if ( Owner.Settings[LStr.RequiredForGrid].ToBool() )
                validFlag      |=   InternalDisplayMasks.RequiredForGrid;
            if ( Owner.Settings[LStr.ValidForGrid].ToBool() )
                validFlag      |=   InternalDisplayMasks.ValidForGrid;
            if ( Owner.Settings[LStr.RequiredForForm].ToBool() )
                validFlag      |=   InternalDisplayMasks.RequiredForForm;
            if ( Owner.Settings[LStr.ValidForForm].ToBool() )
                validFlag      |=   InternalDisplayMasks.ValidForForm;
            if ( Owner.Settings[LStr.ValidForAdvancedFind].ToBool() )
                validFlag      |=   InternalDisplayMasks.ValidForAdvancedFind;
            bool includeAttributeOf             =   Owner.Settings[LStr.SpecialColumn].ToBool();
            econf.InsertAttributesInTable(tb,validFlag,includeAttributeOf,filterNullDisplay,true,false,false);
            // we select by default only needed ones
            validFlag                           =   ( InternalDisplayMasks.RequiredForGrid | InternalDisplayMasks.RequiredForForm );
            string SelVal                       =   econf.ExtractAttributesByFlag(validFlag,true,false,false);
            DataView    dv                      =   tb.DefaultView;
            dv.Sort                             =   CrmStr.strConfDisplayName;
            if ( CrmGridTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid HandleEntityChange installing fields for entityName: {0}, fields: {1}",entityName,SelVal),CrmGridTrace.Sw.Info);
            SettingItem LeadGridFields          =   Owner.Settings[LStr.LeadGridFields];
            LeadGridFields.DataType.ResetDataSource(dv,SelVal);
            if ( CrmGridTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid HandleEntityChange END SelVal: '{0}'.",SelVal),CrmGridTrace.Sw.Info);
        }

        DataTable CreateAttributesTable()
        {
            DataTable tb    =   new DataTable("Attributes");
            DataColumn c1   =   tb.Columns.Add(CrmStr.strConfSchemaName, typeof(string));
            DataColumn c2   =   tb.Columns.Add(CrmStr.strConfDisplayName, typeof(string));
            DataColumn c3   =   tb.Columns.Add(CrmStr.strConfDisplayMask, typeof(int));
            DataColumn c4   =   tb.Columns.Add(CrmStr.strConfAttributeOf, typeof(string));
            DataColumn c6   =   tb.Columns.Add(CrmStr.strConfType, typeof(string));
            DataColumn c8   =   tb.Columns.Add(CrmStr.strConfIsCustomField, typeof(bool));
            DataColumn c9   =   tb.Columns.Add(CrmStr.strConfDefaultValue, typeof(string)); // this will be the string value of the oject
            DataColumn c10  =   tb.Columns.Add(CrmStr.strConfValidForCreate, typeof(bool));
            DataColumn c11  =   tb.Columns.Add(CrmStr.strConfValidForRead, typeof(bool));
            DataColumn c12  =   tb.Columns.Add(CrmStr.strConfValidForUpdate, typeof(bool));

            tb.PrimaryKey   =   new DataColumn[] { c1 };
            return tb;
        }

        public LeadGridSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]LeadGridSI Ctor BEG.",ModuleTraceSwitch.Sw.Info);
            InitSettings(bSettings,pm);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]LeadGridSI Ctor END.",ModuleTraceSwitch.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]LeadGridSI InitSettings BEG.",ModuleTraceSwitch.Sw.Info);
            
            base.InitSettings(bSettings,pm);

            // Separate numerous settings in 3 tabs
            string extgrp                           =   pm.ExtendedResourcesGroup;
            const string extgrp1                    =   "LEADGRID1";
            const string extgrp2                    =   "LEADGRID2";
            
            
            SettingItemSpecial ClassicEntities      =   new SettingItemSpecial(LStr.ClassicEntities,new BooleanDataType());
            ClassicEntities.Required                =   false;
			ClassicEntities.Order                   =   2;
            ClassicEntities.Value                   =   StStr.strFalse;
			ClassicEntities.ExtendedGroupName       =   extgrp;
            ClassicEntities.EnglishName             =	"Classic Entities";
			ClassicEntities.Description             =	"Display well known entities only";
			bSettings.AddSetting(ClassicEntities);           

            SettingItemSpecial PrimaryKeyColumn     =   new SettingItemSpecial(LStr.PrimaryKeyColumn,new BooleanDataType());
            PrimaryKeyColumn.Required               =   false;
			PrimaryKeyColumn.Order                  =   72;
            PrimaryKeyColumn.Value                  =   StStr.strFalse;
			PrimaryKeyColumn.ExtendedGroupName      =   extgrp;
            PrimaryKeyColumn.EnglishName            =	"Primary Key Guid";
			PrimaryKeyColumn.Description            =	"Display the Guid value for the primary key column nammed with entity name";
			bSettings.AddSetting(PrimaryKeyColumn);           

            SettingItemSpecial SpecialColumn        =   new SettingItemSpecial(LStr.SpecialColumn,new BooleanDataType());
            SpecialColumn.Required                  =   false;
			SpecialColumn.Order                     =   73;
            SpecialColumn.Value                     =   StStr.strFalse;
			SpecialColumn.ExtendedGroupName         =   extgrp;
            SpecialColumn.EnglishName               =	"Special Columns";
			SpecialColumn.Description               =	"Display columns that CRM add as complementary columns to existing ones (ended with name,dsc,etc)";
			bSettings.AddSetting(SpecialColumn);           

            SettingItemSpecial WithDisplayName      =   new SettingItemSpecial(LStr.WithDisplayName,new BooleanDataType());
            WithDisplayName.Required                =   false;
			WithDisplayName.Order                   =   75;
            WithDisplayName.Value                   =   StStr.strTrue;
			WithDisplayName.ExtendedGroupName       =   extgrp;
            WithDisplayName.EnglishName             =	"Attributes with Display Name";
			WithDisplayName.Description             =	"Only display attributes that have their displayName not empty";
			bSettings.AddSetting(WithDisplayName);           

            SettingItemSpecial DisplayDateOnly      =   new SettingItemSpecial(LStr.DisplayDateOnly,new BooleanDataType());
            DisplayDateOnly.Required                =   false;
			DisplayDateOnly.Order                   =   76;
            DisplayDateOnly.Value                   =   StStr.strTrue;
			DisplayDateOnly.ExtendedGroupName       =   extgrp;
            DisplayDateOnly.EnglishName             =	"Display Dates as date only";
			DisplayDateOnly.Description             =	"Display date columns as date without time";
			bSettings.AddSetting(DisplayDateOnly);           

            SettingItemSpecial DisplayTimeOnly      =   new SettingItemSpecial(LStr.DisplayTimeOnly,new BooleanDataType());
            DisplayTimeOnly.Required                =   false;
			DisplayTimeOnly.Order                   =   77;
            DisplayTimeOnly.Value                   =   StStr.strFalse;
			DisplayTimeOnly.ExtendedGroupName       =   extgrp;
            DisplayTimeOnly.EnglishName             =	"Display Time column for dates";
			DisplayTimeOnly.Description             =	"When displaying dates only columns, also display a time column.";
			bSettings.AddSetting(DisplayTimeOnly);           

            SettingItemSpecial FormatedAmounts      =   new SettingItemSpecial(LStr.FormatedAmounts,new BooleanDataType());
            FormatedAmounts.Required                =   false;
			FormatedAmounts.Order                   =   77;
            FormatedAmounts.Value                   =   StStr.strFalse;
			FormatedAmounts.ExtendedGroupName       =   extgrp;
            FormatedAmounts.EnglishName             =	"Display Formated Amounts";
			FormatedAmounts.Description             =	"When displaying amounts prefer the formatted CRM value.";
			bSettings.AddSetting(FormatedAmounts);           

            SettingItemSpecial RequiredNone         =   new SettingItemSpecial(LStr.RequiredNone,new BooleanDataType());
            RequiredNone.Required                   =   false;
			RequiredNone.Order                      =   80;
            RequiredNone.Value                      =   StStr.strTrue;
			RequiredNone.ExtendedGroupName          =   extgrp;
            RequiredNone.EnglishName                =	"Attributes not for display";
			RequiredNone.Description                =	"Display attributes that are not marked for display by CRM";
			bSettings.AddSetting(RequiredNone);           

            SettingItemSpecial ObjectTypeCode       =   new SettingItemSpecial(LStr.ObjectTypeCode,new BooleanDataType());
            ObjectTypeCode.Required                 =   false;
			ObjectTypeCode.Order                    =   82;
            ObjectTypeCode.Value                    =   StStr.strTrue;
			ObjectTypeCode.ExtendedGroupName        =   extgrp;
            ObjectTypeCode.EnglishName              =	"Attributes Object Type Code";
			ObjectTypeCode.Description              =	"Display attributes that are marked as ObjectTypeCode by CRM";
			bSettings.AddSetting(ObjectTypeCode);           
            
            SettingItemSpecial PrimaryName          =   new SettingItemSpecial(LStr.PrimaryName,new BooleanDataType());
            PrimaryName.Required                    =   false;
			PrimaryName.Order                       =   84;
            PrimaryName.Value                       =   StStr.strTrue;
			PrimaryName.ExtendedGroupName           =   extgrp;
            PrimaryName.EnglishName                 =	"Attributes Primary Name";
			PrimaryName.Description                 =	"Display attributes that are marked as PrimaryName by CRM";
			bSettings.AddSetting(PrimaryName);           

            SettingItemSpecial RequiredForForm      =   new SettingItemSpecial(LStr.RequiredForForm,new BooleanDataType());
            RequiredForForm.Required                =   false;
			RequiredForForm.Order                   =   90;
            RequiredForForm.Value                   =   StStr.strTrue;
			RequiredForForm.ExtendedGroupName       =   extgrp;
            RequiredForForm.EnglishName             =	"Attributes Required For Form";
			RequiredForForm.Description             =	"Display attributes that are marked as RequiredForForm by CRM";
			bSettings.AddSetting(RequiredForForm);           

            SettingItemSpecial ValidForForm         =   new SettingItemSpecial(LStr.ValidForForm,new BooleanDataType());
            ValidForForm.Required                   =   false;
			ValidForForm.Order                      =   92;
            ValidForForm.Value                      =   StStr.strTrue;
			ValidForForm.ExtendedGroupName          =   extgrp;
            ValidForForm.EnglishName                =	"Attributes Valid For Form";
			ValidForForm.Description                =	"Display attributes that are marked as RequiredForForm by CRM";
			bSettings.AddSetting(ValidForForm);           

            SettingItemSpecial RequiredForGrid      =   new SettingItemSpecial(LStr.RequiredForGrid,new BooleanDataType());
            RequiredForGrid.Required                =   false;
			RequiredForGrid.Order                   =   100;
            RequiredForGrid.Value                   =   StStr.strTrue;
			RequiredForGrid.ExtendedGroupName       =   extgrp;
            RequiredForGrid.EnglishName             =	"Attributes Required For Grid";
			RequiredForGrid.Description             =	"Display attributes that are marked as RequiredForGrid by CRM";
			bSettings.AddSetting(RequiredForGrid);           
            
            SettingItemSpecial ValidForGrid         =   new SettingItemSpecial(LStr.ValidForGrid,new BooleanDataType());
            ValidForGrid.Required                   =   false;
			ValidForGrid.Order                      =   102;
            ValidForGrid.Value                      =   StStr.strTrue;
			ValidForGrid.ExtendedGroupName          =   extgrp;
            ValidForGrid.EnglishName                =	"Attributes valid For Grid";
			ValidForGrid.Description                =	"Display attributes that are marked as ValidForGrid by CRM";
			bSettings.AddSetting(ValidForGrid);           
            
            SettingItemSpecial ValidForAdvancedFind =   new SettingItemSpecial(LStr.ValidForAdvancedFind,new BooleanDataType());
            ValidForAdvancedFind.Required           =   false;
			ValidForAdvancedFind.Order              =   110;
            ValidForAdvancedFind.Value              =   StStr.strTrue;
			ValidForAdvancedFind.ExtendedGroupName  =   extgrp;
            ValidForAdvancedFind.EnglishName        =	"Attributes ValidForAdvancedFind";
			ValidForAdvancedFind.Description        =	"Display attributes that are marked as ValidForAdvancedFind by CRM";
			bSettings.AddSetting(ValidForAdvancedFind);           
            
            SettingItemSpecial IgnoreFormating      =   new SettingItemSpecial(LStr.IgnoreFormating,new BooleanDataType());
            IgnoreFormating.Required                =   false;
			IgnoreFormating.Order                   =   120;
            IgnoreFormating.Value                   =   StStr.strTrue;
			IgnoreFormating.ExtendedGroupName       =   extgrp;
            IgnoreFormating.EnglishName             =	"Ignore formating";
			IgnoreFormating.Description             =	"Ignore formating on export";
			bSettings.AddSetting(IgnoreFormating);           
            
            SettingItemSpecial IgnorePaging         =   new SettingItemSpecial(LStr.IgnorePaging,new BooleanDataType());
            IgnorePaging.Required                   =   false;
			IgnorePaging.Order                      =   130;
            IgnorePaging.Value                      =   StStr.strTrue;
			IgnorePaging.ExtendedGroupName          =   extgrp;
            IgnorePaging.EnglishName                =	"Ignore paging";
			IgnorePaging.Description                =	"Ignore paging on export";
			bSettings.AddSetting(IgnorePaging);           
            
            SettingItemSpecial OpenInNewWindow      =   new SettingItemSpecial(LStr.OpenInNewWindow,new BooleanDataType());
            OpenInNewWindow.Required                =   false;
			OpenInNewWindow.Order                   =   140;
            OpenInNewWindow.Value                   =   StStr.strTrue;
			OpenInNewWindow.ExtendedGroupName       =   extgrp;
            OpenInNewWindow.EnglishName             =	"Open in new window";
			OpenInNewWindow.Description             =	"Open in new window on export";
			bSettings.AddSetting(OpenInNewWindow);           

            SettingItemSpecial AllowFilteringByColumn      =   new SettingItemSpecial(LStr.AllowFilteringByColumn,new BooleanDataType());
            AllowFilteringByColumn.Required                =   false;
			AllowFilteringByColumn.Order                   =   145;
            AllowFilteringByColumn.Value                   =   StStr.strFalse;
			AllowFilteringByColumn.ExtendedGroupName       =   extgrp;
            AllowFilteringByColumn.EnglishName             =	"Allow filtering by column";
			AllowFilteringByColumn.Description             =	"Allow client side filtering of values by column";
			bSettings.AddSetting(AllowFilteringByColumn);           

            SettingItemSpecial GroupingEnabled              =   new SettingItemSpecial(LStr.GroupingEnabled,new BooleanDataType());
            GroupingEnabled.Required                        =   false;
			GroupingEnabled.Order                           =   150;
            GroupingEnabled.Value                           =   StStr.strFalse;
			GroupingEnabled.ExtendedGroupName               =   extgrp;
            GroupingEnabled.EnglishName                     =	"Grouping enabled";
			GroupingEnabled.Description                     =	"Allow client side grouping by columns";
			bSettings.AddSetting(GroupingEnabled);           
            
            /// Second settings Tab: entity and Fields selection

            ArrayList are                                   =   GetAllEntities(true);
            if ( CrmGridTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid Ctor Nb entities: {0}",are.Count),CrmGridTrace.Sw.Info);
            CustomListDataType ECombo                       =   new CustomListDataType(are, "displayName", "entityName");
            ECombo.SortOrder                                =   RadComboBoxSort.Ascending;
            SettingItemSpecial LeadGridEntity               =   new SettingItemSpecial(LStr.LeadGridEntity,ECombo);
			LeadGridEntity.Required			                =	true;
			LeadGridEntity.Order			                =	210;
            LeadGridEntity.ExtendedGroupName                =   extgrp1;
            LeadGridEntity.Group                            =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
            LeadGridEntity.Value			                =	CrmStr.account; // default value
			LeadGridEntity.Description		                =	"Select an entity to display";
            LeadGridEntity.EnglishName		                =	"Entity";
            LeadGridEntity.AddDependency(ClassicEntities,new SettingItemsEventHandler(HandleFilterEntity));
			bSettings.AddSetting(LeadGridEntity);
            
            DataTable tb                                    =   CreateAttributesTable();
            string SelVal                                   =   string.Empty;

            EntityConfig econf                              =   GetEntityConfig(CrmStr.account);
            InternalDisplayMasks validFlag                  =   InternalDisplayMasks.None|InternalDisplayMasks.ObjectTypeCode|
                                        InternalDisplayMasks.PrimaryName|InternalDisplayMasks.RequiredForGrid|
                                    InternalDisplayMasks.RequiredForGrid |InternalDisplayMasks.RequiredForForm|
                                    InternalDisplayMasks.ValidForForm|InternalDisplayMasks.ValidForAdvancedFind;
            econf.InsertAttributesInTable(tb,validFlag,false,true,true,false,false);
            //extract default selected values: we take only mandatory att for grid and form
            validFlag                                       =   ( InternalDisplayMasks.RequiredForGrid | InternalDisplayMasks.RequiredForForm );
            SelVal                                          =   econf.ExtractAttributesByFlag(validFlag,true,false,false);
            if ( CrmGridTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid Ctor ExtractAttributesByFlag: {0}",SelVal),CrmGridTrace.Sw.Info);
            DataView    dv                                  =   tb.DefaultView;
            dv.Sort                                         =   CrmStr.strConfDisplayName;
            if ( CrmGridTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid Ctor tb.Sort: {0}",tb.DefaultView.Sort),CrmGridTrace.Sw.Info);
            SelListBoxDataType SelTree                      =   new SelListBoxDataType(dv,CrmStr.strConfDisplayName,CrmStr.strConfSchemaName);
            SelTree.ListBoxHeight                           =   new Unit("400px");
            SettingItemSpecial LeadGridFields               =   new SettingItemSpecial(LStr.LeadGridFields,SelTree);
			LeadGridFields.Required			                =	false;
			LeadGridFields.Order			                =	220;
            LeadGridFields.Value                            =   SelVal;
			LeadGridFields.ExtendedGroupName                =   extgrp1;
            LeadGridFields.Group                            =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
			LeadGridFields.Description		                =	"Select fields to display";
            LeadGridFields.EnglishName		                =	"Fields";
            LeadGridFields.AddDependency(LeadGridEntity,new SettingItemsEventHandler(HandleEntityChange));
			bSettings.AddSetting(LeadGridFields);
            
            SettingItemSpecial Filter                       =   new SettingItemSpecial(LStr.Filter,new StringDataType());
            Filter.Required                                 =   false;
			Filter.Order                                    =   250;
            Filter.Value                                    =   string.Empty;
			Filter.ExtendedGroupName                        =   extgrp1;
            Filter.Group                                    =   SettingItemGroup.MODULE_SPECIAL_SETTINGS1;
            Filter.EnglishName                              =	"Request filter";
			Filter.Description                              =   "Sql like filter to select records";
			bSettings.AddSetting(Filter);           
            /// Third settings Tab

			SettingItemSpecial gScrolling	                =	new SettingItemSpecial(LStr.Scroll,new BooleanDataType());
			gScrolling.Order			                    =	330;
            gScrolling.Value			                    =	StStr.strTrue;
			gScrolling.ExtendedGroupName                    =   extgrp2;
            gScrolling.Group                                =   SettingItemGroup.MODULE_SPECIAL_SETTINGS2;
			gScrolling.Description		                    =	"True if the grid will be displayed using Scrolling";
            gScrolling.EnglishName		                    =	"Scrolling mode for Grid";
			bSettings.AddSetting(gScrolling);

			SettingItemSpecial gPaging		        =	new SettingItemSpecial(LStr.Paging,new BooleanDataType());
			gPaging.Order			                =	340;
            gPaging.Required                        =   false;
            gPaging.Value			                =	StStr.strTrue;
			gPaging.ExtendedGroupName               =   extgrp2;
            gPaging.Group                           =   SettingItemGroup.MODULE_SPECIAL_SETTINGS2;
			gPaging.Description		                =	"True if the grid will be displayed using Paging";
            gPaging.EnglishName		                =	"Page mode for Grid";
			bSettings.AddSetting(gPaging);

			SettingItemSpecial pgSz		            =	new SettingItemSpecial(LStr.PageSz,new IntegerDataType()); 
            pgSz.Required                           =   false;
			pgSz.Required			                =	true;
			pgSz.MinValue			                =	10;
			pgSz.MaxValue			                =	500;
			pgSz.Order				                =	350;
            pgSz.Value				                =	"20";
			pgSz.ExtendedGroupName                  =   extgrp2;
            pgSz.Group                              =   SettingItemGroup.MODULE_SPECIAL_SETTINGS2;
			pgSz.Description		                =	"Number of records displayed in each page";
            pgSz.EnglishName		                =   "Grid Page Size";
			bSettings.AddSetting(pgSz);
		
			SettingItemSpecial imperso              =   new SettingItemSpecial(LStr.ShouldImpersonate,new BooleanDataType());
            imperso.Value                           =   StStr.strTrue;
            imperso.Order                           =   360;
			imperso.ExtendedGroupName               =   extgrp2;
            imperso.Group                           =   SettingItemGroup.MODULE_SPECIAL_SETTINGS2;
            imperso.EnglishName                     =   "Impersonate CRM access";
            imperso.Description                     =   "If No, the current user will be used to access CRM, if the user is not a crm user, or he is not logged on the domain it will generate failures";
            bSettings.AddSetting(imperso);

			SettingItemSpecial detectFormAuth       =   new SettingItemSpecial(LStr.DetectFormAuth,new BooleanDataType());
            detectFormAuth.Value                    =   StStr.strTrue;
            detectFormAuth.Order                    =   365;
			detectFormAuth.ExtendedGroupName        =   extgrp2;
            detectFormAuth.Group                    =   SettingItemGroup.MODULE_SPECIAL_SETTINGS2;
            detectFormAuth.EnglishName              =   "Detect form authentication";
            detectFormAuth.Description              =   "When in form authentication and user authentified, uses its associated account to filter";
            bSettings.AddSetting(detectFormAuth);

			
            WSListDataType defAcc                   =   new WSListDataType(CrmStr.systemuser,"name", "ID");
            SettingItemSpecial selUser              =   new SettingItemSpecial(LStr.ImpersonateUser,defAcc);
            // default == CRMDefaultAccount or first
            ADNDynSystemUser wsys                    =   null;
            if (!string.IsNullOrEmpty(Config.CRMDefaultAccount))
            {
                string domainName                   =   string.Format("{0}\\{1}",Config.CRMDefaultAccountDomain,Config.CRMDefaultAccount);
                wsys                                =   Wrapper.Util.FindSystemUserByDomainName(domainName);
            }
            if (wsys != null)
            {
                selUser.Value                       =   wsys.systemuserid.ToString();
                defAcc.DisplayTextValue             =   wsys.fullname;
            }
			selUser.Order                           =   370;

            selUser.ExtendedGroupName               =   extgrp2;
            selUser.Group                           =   SettingItemGroup.MODULE_SPECIAL_SETTINGS2;
            selUser.EnglishName                     =	"Impersonate CRM access filter";
			selUser.Description                     =	"Choose the user that will be used to access the CRM, display will be affected by the rights allocated to this user";
			bSettings.AddSetting(selUser);           
            

            // Flag to allow acces to settings by custom controls from Core
            inCtor                                  =   false;
            if ( CrmGridTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]LeadGridSI InitSettings END",(CrmGridTrace.Sw.TraceVerbose) ? CrmGridTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
        }
    }

    /// <summary>
    ///	LeadGrid display any entity selected values in a RadGrid.
    /// </summary>
	public partial class LeadGrid : PortalCRMModuleControl
    {
		/// <summary>
        /// CTor 
        /// </summary>
        public LeadGrid()
        {
            if ( CrmGridTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]LeadGrid Ctor BEG",(CrmGridTrace.Sw.TraceVerbose ) ? CrmGridTrace.Sw.Info :ModuleTraceSwitch.Sw.Info);
            if ( CrmGridTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]LeadGrid Ctor END",(CrmGridTrace.Sw.TraceVerbose) ? CrmGridTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
        }
        
        public override string ExtendedResourcesGroup 
		{
            get
            {
                const string extgrp                     =   "LEADGRID";
                return extgrp;
            }
		}

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new LeadGridSI(bSettings,this);
        }

        void InitExport()
		{
            RadGrid1.ExportSettings.ExportOnlyData  =   Settings[LStr.IgnoreFormating].ToBool();
            RadGrid1.ExportSettings.IgnorePaging    =   Settings[LStr.IgnorePaging].ToBool();
            RadGrid1.ExportSettings.OpenInNewWindow =   Settings[LStr.OpenInNewWindow].ToBool();
        }
		protected void BtnExport2XL()
		{
            InitExport();
            RadGrid1.MasterTableView.ExportToExcel();
        }

		protected void BtnExport2Wrd()
		{
            InitExport();
            RadGrid1.MasterTableView.ExportToWord();
        }
  
		protected void BtnExport2Pdf()
		{
            InitExport();
            RadGrid1.MasterTableView.ExportToPdf();
        }
  
        protected void BtnExport2Csv()
		{
            InitExport();
            RadGrid1.MasterTableView.ExportToCSV();
        }
  
        protected void Page_Load(object sender, EventArgs e)
        {
           if ( CrmGridTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose )
               Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid Page_Load BEG IsPostBack: {0}, IsInAsyncPostBack: {1}",IsPostBack,IsInAsyncPostBack),( CrmGridTrace.Sw.TraceVerbose ) ? CrmGridTrace.Sw.Info :ModuleTraceSwitch.Sw.Info);
           if ( !IsPostBack )
           {
				//force paging according settings
				RadGrid1.AllowPaging	        =	Settings[LStr.Paging].ToBool();
                RadGrid1.AllowFilteringByColumn =	Settings[LStr.AllowFilteringByColumn].ToBool();
                RadGrid1.GroupingEnabled        =	Settings[LStr.GroupingEnabled].ToBool();
				if ( RadGrid1.AllowPaging )
						RadGrid1.PageSize = Settings[LStr.PageSz].ToInt();
            }
           if ( CrmGridTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose )
               Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid Page_Load END IsPostBack: {0}",IsPostBack),(CrmGridTrace.Sw.TraceVerbose)? CrmGridTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
         }

		/// <summary>
		/// Generates a DataTable to display query result with selected columns
		/// </summary>
		DataTable CreateLeadTb()
		{
            if ( CrmGridTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]LeadGrid CreateLeadTb BEG",CrmGridTrace.Sw.Info);
			// Create the column set which indicates the fields to be retrieved.
            InternalColumnSetBase cols              =   null;
            string entityName                       =   Settings[LStr.LeadGridEntity].Value;
            string AttrVal                          =   Settings[LStr.LeadGridFields].Value;
            if ( CrmGridTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid CreateLeadTb entityName: {0}, Fields: {1}",entityName,AttrVal ),CrmGridTrace.Sw.Info);
            bool ok                                 =   true;
            if ( !string.IsNullOrEmpty(AttrVal) )
            {
                cols                                =   new InternalColumnSet();
                string[] attribs                    =   AttrVal.Split(new char[]{';'},StringSplitOptions.RemoveEmptyEntries);
                // we check attribs to correct a synch error between entityName and fields
                EntityConfig conf                   =   ((LeadGridSI)PortalModuleInitializer).GetEntityConfig(entityName);
                string PrimaryKey                   =   conf.PrimaryKey;
                List<string> newAtt                 =   new List<string>(); 
                // Ensure PrimaryKey is there because we need it in tb creation
                if ( !string.IsNullOrEmpty(PrimaryKey) )
                {
                    bool pOk                        =   false;
                    for (int i = 0; i < attribs.Length ; i++)
                        if ( attribs[i] == PrimaryKey )
                        {
                            pOk                     =   true;
                            break;
                        }
                    if ( !pOk )
                        newAtt.Add(PrimaryKey);
                }
                if ( CrmGridTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid CreateLeadTb attribs.Length: {0}",attribs.Length),CrmGridTrace.Sw.Info);
                for (int i = 0; i < attribs.Length && ok ; i++)
                {
                    string strschemaName            =   attribs[i];
                    if ( CrmGridTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid CreateLeadTb i: {0}, strschemaName: [{1}]", i, strschemaName),CrmGridTrace.Sw.Info);
                    InternalAttributeMetadata att   =   conf[strschemaName];
                    if ( att == null)
                    {
                        ok                          =   false;
                        if ( CrmGridTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid CreateLeadTb NOT in Metadata i: {0}, strschemaName: [{1}]", i, strschemaName),CrmGridTrace.Sw.Info);
                        break;
                    }
                    string attributeOf              =   Wrapper.Util.ExtractAttributeFieldAsString(att,InternalAttributeFields.AttributeOf);
                    string DisplayName              =   Wrapper.Util.ExtractAttributeFieldAsString(att,InternalAttributeFields.DisplayName);
                    AttributeInternalType attributType  =   (AttributeInternalType)Wrapper.Util.ExtractAttributeFieldAsInt(att,InternalAttributeFields.AttributeType);
                    string strAttNm                 =   attributType.ToString();
                    if ( !string.IsNullOrEmpty(attributeOf) )
                    {
                        if ( CrmGridTrace.Sw.TraceVerbose )
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid CreateLeadTb strschemaName: {0}, attributeOf: {1}", strschemaName, attributeOf),CrmGridTrace.Sw.Info);
                        continue;
                    }
                    newAtt.Add(strschemaName);
                    if ( CrmGridTrace.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid CreateLeadTb i: {0}, added attribs: [{1}]", i, attribs[i]),CrmGridTrace.Sw.Info);
                }
                if (ok)
                {
                    attribs                         =   newAtt.ToArray();
                    ((InternalColumnSet)cols).Attributes = attribs;
                }
            }
            bool takeAllCols                        =   ( string.IsNullOrEmpty(AttrVal) || !ok );
            if ( CrmGridTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid CreateLeadTb takeAllCols: {0}.", takeAllCols),CrmGridTrace.Sw.Info);
            // if  selection is null or synch error with selected fields we take everything
            // TBD-> take what can be displayed
            if ( takeAllCols )
                cols                                =   new InternalAllColumns();
            // send query to server
            InternalQueryExpression query           =   new InternalQueryExpression();
            InternalFilterExpression filter         =   new InternalFilterExpression();
            bool makeRollup                         =   false;
            AddonNiceMembershipUser user            =   null;
            if ( Settings[LStr.DetectFormAuth].ToBool() && 
                ( Config.AuthenticationMode == AuthenticationMode.Forms ) && UserLogged )
            {
                user                                =   (AddonNiceMembershipUser)Membership.GetUser();
                if ( CrmGridTrace.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid CreateLeadTb Authentication Forms and user logged filtering on typeName: {0}, CrmId: {1}."
                        , user.typeName,user.CrmId),CrmGridTrace.Sw.Info);
                switch ( entityName )
                {
                    case CrmStr.activitypointer:
                    case CrmStr.annotation:
                    case CrmStr.contract:
                    case CrmStr.incident:
                    case CrmStr.opportunity:
                    case CrmStr.salesorder:
                    case CrmStr.invoice:
                    case CrmStr.quote:
                        switch ((ADNTypeCodes)user.typeCode)
                        {
                            case ADNTypeCodes.Account:
                            case ADNTypeCodes.Contact:
                                makeRollup          =   true;
                                break;
                        }
                        break;
                }
            }
            // No conditions in filter
            query.ColumnSet                         =   cols;
            query.Criteria                          =   filter;
            query.EntityName                        =   entityName;
            DataTable   tb                          =   null;
            if ( CrmGridTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid CreateLeadTb makeRollup: {0}.", makeRollup),CrmGridTrace.Sw.Info);
            try
            {
                if ( ( Config.AuthenticationMode != AuthenticationMode.Forms ) || UserLogged )
                {
                    GenericDynQueryMultiple<DynEntity> selectAll = new GenericDynQueryMultiple<DynEntity>(PortalSecurity.Wrapper,ResetWrapper,entityName);
                    if (makeRollup)
                    {
                        tb                          =   selectAll.RollupDatatable(user.typeName,user.CrmId, query);
                    }
                    else 
                    {
                        tb                          =   selectAll.retrieveDatatable(query);
                    }
                }
            }
            catch (Exception ex)
            {
                if ( ModuleTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]LeadGrid CreateLeadTb ex: {0}",ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
            if ( CrmGridTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid CreateLeadTb END count: {0}.", (tb != null) ? tb.Rows.Count:0),CrmGridTrace.Sw.Info);
            return tb;
		}

 		#region General implementation
		/// <summary>
		/// AddonNice module key
		/// </summary>
		public override Guid GuidID
        {
            get
            {
                return new Guid("{BD5908CF-ECB1-470d-AC6C-F77A7350C05B}");
            }
        }
		#endregion General implementation

        #region RadGrid internals

        void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
           if ( CrmGridTrace.Sw.TraceVerbose )
               Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid RadGrid1_NeedDataSource BEG RebindReason: {0}",e.RebindReason),CrmGridTrace.Sw.Info);
		   RadGrid1.DataSource	=	CreateLeadTb();
           if ( CrmGridTrace.Sw.TraceVerbose )
               Trace2.WriteLine("[V]LeadGrid RadGrid1_NeedDataSource END.",CrmGridTrace.Sw.Info);
        }

        void RadGrid1_ColumnCreated(object sender, GridColumnCreatedEventArgs e)
        {
            if ( !(e.Column is GridBoundColumn))
                return;
            string colName                  =   ((GridBoundColumn)e.Column).DataField;
            if ( CrmGridTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid RadGrid1_ColumnCreated BEG colName: {0}, HeaderText: {1}",colName,e.Column.HeaderText ),CrmGridTrace.Sw.Info);
            if (colName.IndexOf(CrmStr.InternalRowTypecode) > 0 ||
                    colName.IndexOf(CrmStr.InternalRowVal) > 0)
            {
                //e.Column.Display            =   false;
                e.Column.Visible            =   false;
                return;
            }
            string entityName               =   Settings[LStr.LeadGridEntity].Value;
            EntityConfig econf              =   ((LeadGridSI)PortalModuleInitializer).GetEntityConfig(entityName);
            InternalAttributeMetadata att   =   econf[colName];
            if ( att == null )
            {
                int idx                     =   colName.IndexOf(CrmStr.InternalRowDate);
                if( idx > -1 )
                {
                    if ( !Settings[LStr.DisplayDateOnly].ToBool() )
                    {
                        e.Column.Visible    =   false;
                        //e.Column.Display    =   false;
                    }
                    string col2Name         =   colName.Substring(0,idx);
                    att                     =   econf[col2Name]; // to fet column header name
                }
                else if( colName.IndexOf(CrmStr.InternalRowTime) > -1 )
                {
                    if ( !Settings[LStr.DisplayDateOnly].ToBool() || !Settings[LStr.DisplayTimeOnly].ToBool() )
                    {
                        e.Column.Visible    =   false;
                        //e.Column.Display    =   false;
                    }
                }
                idx                         =   colName.IndexOf(CrmStr.InternalRowFormat);
                if( idx > -1 )
                {
                    if ( !Settings[LStr.FormatedAmounts].ToBool() )
                    {
                        e.Column.Visible    =   false;
                        //e.Column.Display    =   false;
                    }
                    string col2Name         =   colName.Substring(0,idx);
                    att                     =   econf[col2Name]; // to fet column header name
                }
                if ( att == null )
                    return;
            }
            else
            {
                AttributeInternalType attType                     =   (AttributeInternalType)Wrapper.Util.ExtractAttributeFieldAsInt(att,InternalAttributeFields.AttributeType);
                // we will display the date only column instead of default datetime column
                if ( ( attType == AttributeInternalType.DateTime ) && Settings[LStr.DisplayDateOnly].ToBool() )
                {
                    e.Column.Visible        =   false;
                    //e.Column.Display        =   false;
                    return;
                }
                else if ( Settings[LStr.FormatedAmounts].ToBool() &&
                    ( ( attType == AttributeInternalType.Decimal ) || 
                      ( attType == AttributeInternalType.Float )  ||
                      ( attType == AttributeInternalType.Integer )  ||
                      ( attType == AttributeInternalType.Money )  
                    )   )
                {
                    e.Column.Visible        =   false;
                    //e.Column.Display            =   false;
                    return;
                }
            }
            string PrimaryKeyName           =   econf.PrimaryKey;
            bool displayPrimaryKey          =   Settings[LStr.PrimaryKeyColumn].ToBool();
            if (!displayPrimaryKey && PrimaryKeyName.Equals(colName))
            {
                e.Column.Visible            =   false;
                //e.Column.Display            =   false;
                return;
            }
            string DisplayName              =   Wrapper.Util.ExtractAttributeFieldAsString(att,InternalAttributeFields.DisplayName);
            if ( string.IsNullOrEmpty(DisplayName) )
                return;
            e.Column.HeaderText             =   DisplayName;
        }

        void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (CrmGridTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid RadGrid1_ItemDataBound BEG ItemType: {0}, DataItem: {1}", e.Item.ItemType,e.Item.DataItem), CrmGridTrace.Sw.Info);
            if (!(e.Item.ItemType == GridItemType.Item ) &&
                !(e.Item.ItemType == GridItemType.AlternatingItem ))
                return;
            if ( !(e.Item is GridDataItem ) )
                return;
            GridDataItem item                   =   (GridDataItem)e.Item;

            string entityName               =   Settings[LStr.LeadGridEntity].Value;
            string AttrVal                  =   Settings[LStr.LeadGridFields].Value.TrimEnd(new char[]{';'});
            if ( CrmGridTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid RadGrid1_ItemDataBound entityName: {0}, Fields: {1}",entityName,AttrVal ),CrmGridTrace.Sw.Info);
            bool ok             = true;
            if ( string.IsNullOrEmpty(AttrVal) )
                return;
            string[] attribs                    =   AttrVal.Split(new char[]{';'},StringSplitOptions.RemoveEmptyEntries);
            EntityConfig conf                   =   ((LeadGridSI)PortalModuleInitializer).GetEntityConfig(entityName);
            for (int i = 0; i < attribs.Length && ok ; i++)
            {
                string strschemaName                =   attribs[i];
                InternalAttributeMetadata att       =   conf[strschemaName];
                AttributeInternalType attributType  =   (AttributeInternalType)Wrapper.Util.ExtractAttributeFieldAsInt(att,InternalAttributeFields.AttributeType);
                InternalDisplayMasks  attributDM    =   (InternalDisplayMasks)Wrapper.Util.ExtractAttributeFieldAsInt(att,InternalAttributeFields.DisplayMask);
                string strVal                       =   item[strschemaName].Text.Trim();
                if ( string.IsNullOrEmpty(strVal) || strVal.Equals(StStr.HTML_SPACE)  ) // Null value 
                    continue;
                if (CrmGridTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid RadGrid1_ItemDataBound col: {0}, value: {1}",strschemaName,strVal), CrmGridTrace.Sw.Info);
                string strVal2                      =   string.Empty;

                if ( attributDM == InternalDisplayMasks.ObjectTypeCode ||
                    (strschemaName == CrmStr.objecttypecode && attributType == AttributeInternalType.Picklist) )
                {
                    attributType = AttributeInternalType.EntityNameReference;
                    if ( CRMQueryTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid RadGrid1_ItemDataBound changing type for Key: {0}.",strschemaName),CRMQueryTraceSwitch.Sw.Info);
                }
                switch (attributType)
                {
                    case AttributeInternalType.Status:
                    {
                        strVal2                 =   item[strschemaName+CrmStr.InternalRowTypecode].Text.Trim();
                        if (CrmGridTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid RadGrid1_ItemDataBound StatusVal: {0}",strVal2), CrmGridTrace.Sw.Info);
                        break;
                    }
                    case AttributeInternalType.Picklist:
                    {
                        strVal2                 =   item[strschemaName+CrmStr.InternalRowTypecode].Text.Trim();
                        if (CrmGridTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid RadGrid1_ItemDataBound PickListVal: {0}",strVal2), CrmGridTrace.Sw.Info);
                        break;
                    }
                    case AttributeInternalType.Owner:
                    {
                        Guid ownerId            =   new Guid(strVal);
                        if (CrmGridTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid RadGrid1_ItemDataBound ownerId: {0}",ownerId), CrmGridTrace.Sw.Info);
                        string suDisplay        =   item[strschemaName+CrmStr.InternalRowVal].Text.Trim();
                        ADNDynSystemUser sysuser =   DynEntity.FindOwner(Wrapper,ownerId,suDisplay);
                        strVal2                 =   sysuser.fullname;
                        if (strVal2.Equals(string.Empty))
                        {
                            strVal2                 =   suDisplay;
                        }
                        if (CrmGridTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid RadGrid1_ItemDataBound Owner: {0}",strVal2), CrmGridTrace.Sw.Info);
                        break;
                    }
                    case AttributeInternalType.UniqueIdentifier:
                        break;
                    case AttributeInternalType.PrimaryKey:
                    {
                        Guid CrmId            =   new Guid(strVal);
                        if (CrmGridTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid RadGrid1_ItemDataBound UniqueIdentifier: {0}",CrmId), CrmGridTrace.Sw.Info);
                        DynEntity dynEnt    =   null;
                        switch (entityName)
                        {
                            case CrmStr.productassociation:
                                if (strschemaName == CrmStr.associatedproduct || strschemaName == CrmStr.productid)
                                {
                                    dynEnt    =   DynEntity.FindUniqueIdentifier(Wrapper,strschemaName,CrmStr.product,CrmId);
                                }
                                break;
                            case CrmStr.productsalesliterature:
                                if ( strschemaName == CrmStr.productid)
                                {
                                    dynEnt    =   DynEntity.FindUniqueIdentifier(Wrapper,strschemaName,CrmStr.product,CrmId);
                                }
                                else if ( strschemaName == CrmStr.salesliteratureid)
                                {
                                    dynEnt    =   DynEntity.FindUniqueIdentifier(Wrapper,strschemaName,CrmStr.salesliterature,CrmId);
                                }
                                break;
                            case CrmStr.productsubstitute:
                                if (strschemaName == CrmStr.substitutedproductid || strschemaName == CrmStr.productid)
                                {
                                    dynEnt    =   DynEntity.FindUniqueIdentifier(Wrapper,strschemaName,CrmStr.product,CrmId);
                                }
                                break;
                            case CrmStr.contact:
                            case CrmStr.appointment:
                            case CrmStr.serviceappointment:
                            case CrmStr.phonecall:
                            case CrmStr.letter:
                            case CrmStr.fax:
                            case CrmStr.task:
                                if (strschemaName == CrmStr.subscriptionid)
                                {
                                    dynEnt    =   DynEntity.FindUniqueIdentifier(Wrapper,strschemaName,CrmStr.subscription,CrmId);
                                }
                                break;
                            case CrmStr.uom:
                            case CrmStr.systemuser:
                            case CrmStr.site:
                            case CrmStr.relationshiprolemap:
                            case CrmStr.team:
                            case CrmStr.kbarticlecomment:
                            case CrmStr.calendarrule:
                            case CrmStr.discount:
                            case CrmStr.salesliteratureitem:
                            case CrmStr.productpricelevel:
                                if (strschemaName == CrmStr.businessunitid)
                                {
                                    dynEnt    =   DynEntity.FindUniqueIdentifier(Wrapper,strschemaName,CrmStr.businessunit,CrmId);
                                }
                                else if (strschemaName == CrmStr.organizationid)
                                {
                                    dynEnt    =   DynEntity.FindUniqueIdentifier(Wrapper,strschemaName,CrmStr.organization,CrmId);
                                }
                                break;
                            case CrmStr.calendar:
                                if (strschemaName == CrmStr.primaryuserid)
                                {
                                    dynEnt    =   DynEntity.FindUniqueIdentifier(Wrapper,strschemaName,CrmStr.systemuser,CrmId);
                                }
                                break;
                            case CrmStr.quote:
                            case CrmStr.salesorder:
                            case CrmStr.invoice:
                                if ( strschemaName == CrmStr.shipto_addressid || strschemaName == CrmStr.billto_addressid )
                                {
                                    dynEnt    =   DynEntity.FindUniqueIdentifier(Wrapper,strschemaName,CrmStr.customeraddress,CrmId);
                                }
                                    // TBC : these entities have no owninguser but ownerid 
                                else if (strschemaName == CrmStr.owninguser)
                                {
                                    dynEnt    =   DynEntity.FindUniqueIdentifier(Wrapper,strschemaName,CrmStr.systemuser,CrmId);
                                }
                                    // TBC : owningbusinessunit for these entities is a lookup, could not be found as primarykey
                                else if (strschemaName == CrmStr.owningbusinessunit)
                                {
                                    dynEnt    =   DynEntity.FindUniqueIdentifier(Wrapper,strschemaName,CrmStr.businessunit,CrmId);
                                }
                                break;

                            case CrmStr.salesorderdetail:
                            case CrmStr.invoicedetail:
                            case CrmStr.quotedetail:
                            case CrmStr.orderdetail:
                            case CrmStr.contractdetail:
                            case CrmStr.opportunityproduct:
                            case CrmStr.listmember:
                            case CrmStr.campaignitem:
                            case CrmStr.campaignactivityitem:
                                if ( strschemaName == CrmStr.shipto_addressid || strschemaName == CrmStr.billto_addressid )
                                {
                                    dynEnt    =   DynEntity.FindUniqueIdentifier(Wrapper,strschemaName,CrmStr.customeraddress,CrmId);
                                }
                                else if (strschemaName == CrmStr.owninguser)
                                {
                                    dynEnt    =   DynEntity.FindUniqueIdentifier(Wrapper,strschemaName,CrmStr.systemuser,CrmId);
                                }
                                else if (strschemaName == CrmStr.owningbusinessunit)
                                {
                                    dynEnt    =   DynEntity.FindUniqueIdentifier(Wrapper,strschemaName,CrmStr.businessunit,CrmId);
                                }
                                break;
                            case CrmStr.service:
                            case CrmStr.resource:
                                if (strschemaName == CrmStr.calendarid)
                                {
                                    dynEnt    =   DynEntity.FindUniqueIdentifier(Wrapper,strschemaName,CrmStr.calendar,CrmId);
                                }
                                break;
                            case CrmStr.organization:
                                if (strschemaName == CrmStr.systemuserid || strschemaName == CrmStr.supportuserid)
                                {
                                    dynEnt    =   DynEntity.FindUniqueIdentifier(Wrapper,strschemaName,CrmStr.systemuser,CrmId);
                                }
                                else if (strschemaName == CrmStr.businessclosurecalendarid )
                                {
                                    dynEnt    =   DynEntity.FindUniqueIdentifier(Wrapper,strschemaName,CrmStr.calendar,CrmId);
                                }
                                else if (strschemaName == CrmStr.integrationuserid )
                                {
                                    dynEnt    =   DynEntity.FindUniqueIdentifier(Wrapper,strschemaName,CrmStr.systemuser,CrmId);
                                }
                                break;
                        }
                        if ( dynEnt == null )
                            break;
                         strVal2             =   dynEnt.PrimaryFieldStringValue;
                        if (CrmGridTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid RadGrid1_ItemDataBound UniqueIdentifier: {0}",strVal2), CrmGridTrace.Sw.Info);
                        break;
                    }
                    case AttributeInternalType.DateTime:
                        break;
                    case AttributeInternalType.Lookup:
                    {
                        Guid CrmId              =   new Guid(strVal);
                        if (CrmGridTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid RadGrid1_ItemDataBound lookup CrmId: {0}",CrmId), CrmGridTrace.Sw.Info);
                        string typenm           =   item[strschemaName+CrmStr.InternalRowTypecode].Text.Trim();
                        if (CrmGridTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid RadGrid1_ItemDataBound lookup typename: [{0}]",typenm), CrmGridTrace.Sw.Info);
                        string lkDisplay        =   item[strschemaName+CrmStr.InternalRowVal].Text.Trim();
                        DynEntity dEnt          = DynEntity.RetrieveLookup(Wrapper,entityName,conf,strschemaName,CrmId,lkDisplay);
                        if ( dEnt != null )
                            strVal2             =   dEnt.PrimaryFieldStringValue;
                            if (CrmGridTrace.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid RadGrid1_ItemDataBound lookup: {0}",strVal2), CrmGridTrace.Sw.Info);
                        if (strVal2.Equals(string.Empty))
                        {
                            strVal2                 =   lkDisplay;
                        }
                        break;
                    }
                    case AttributeInternalType.Customer:
                    {
                        Guid CrmId              =   new Guid(strVal);
                        if (CrmGridTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid RadGrid1_ItemDataBound Customer CrmId: {0}",CrmId), CrmGridTrace.Sw.Info);
                        string typenm           =   item[strschemaName+CrmStr.InternalRowTypecode].Text.Trim();
                        if (CrmGridTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid RadGrid1_ItemDataBound Customer typename: [{0}]",typenm), CrmGridTrace.Sw.Info);
                        string cuDisplay        =   item[strschemaName+CrmStr.InternalRowVal].Text.Trim();
                        if ( !typenm.Equals(string.Empty) )
                        {
                            DynEntity dEnt          =   DynEntity.RetrieveCustomer(Wrapper,entityName,strschemaName,CrmId,typenm,cuDisplay);
                            if ( dEnt != null )
                                strVal2                 =   dEnt.PrimaryFieldStringValue;
                            if (CrmGridTrace.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid RadGrid1_ItemDataBound Customer: {0}",strVal2), CrmGridTrace.Sw.Info);
                        }
                        if (strVal2.Equals(string.Empty))
                        {
                            strVal2                 =   cuDisplay;
                        }
                        break;
                    }
                }
                if (CrmGridTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]LeadGrid RadGrid1_ItemDataBound col: {0}, oldvalue: {1}, new value: {2}",strschemaName,strVal,strVal2), CrmGridTrace.Sw.Info);
                if ( strVal2 != string.Empty )
                    item[strschemaName].Text        =   strVal2;
            }

            if (CrmGridTrace.Sw.TraceVerbose)
                Trace2.WriteLine("[V]LeadGrid RadGrid1_ItemDataBound END.", CrmGridTrace.Sw.Info);
        }
        
        void RadGrid1_ItemCommand(object source,GridCommandEventArgs e)
        {
            if ( CrmGridTrace.Sw.TraceVerbose )
                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[[V]ExportOrders RadGrid1_ItemCommand BEG CommandName: {0}.", e.CommandName),CrmGridTrace.Sw.Info);
            if ( e.CommandName == RadGrid.ExportToExcelCommandName )
            {
                BtnExport2XL();
                e.Canceled  =   true;
                return;
            }
            
            if ( e.CommandName == RadGrid.ExportToWordCommandName )
            {
                BtnExport2Wrd();
                e.Canceled  =   true;
                return;
            }
            
            if ( e.CommandName == RadGrid.ExportToCsvCommandName )
            {
                BtnExport2Csv();
                e.Canceled  =   true;
                return;
            }
            if ( e.CommandName == RadGrid.ExportToPdfCommandName )
            {
                BtnExport2Pdf();
                e.Canceled  =   true;
                return;
            }
            if ( CrmGridTrace.Sw.TraceVerbose )
                Trace2.WriteLine(string.Format(CultureInfo.InvariantCulture,"[[V]ExportOrders RadGrid1_ItemCommand END CommandName: {0}.", e.CommandName),CrmGridTrace.Sw.Info);
        }

        /// <summary>
        /// Just here to hide the create button of Telerik CommandItem
        /// </summary>
        void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridCommandItem)
            {
                // the link button
                LinkButton btn  =   (LinkButton)e.Item.FindControl("InitInsertButton");
                if ( btn != null )
                    btn.Visible =   false;
                //the image
                Control img     =   e.Item.FindControl("AddNewRecordButton");
                if ( img != null )
                    img.Visible =   false;
            }
        }

        #endregion RadGrid internals

        #region Std Overrides

		public override void Page_PreInit(object sender, EventArgs e)
        {
           if ( CrmGridTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose )
               Trace2.WriteLine( "[V]LeadGrid Page_PreInit BEG.",(CrmGridTrace.Sw.TraceVerbose) ? CrmGridTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
            base.Page_PreInit(sender, e);
           if ( CrmGridTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose )
               Trace2.WriteLine( "[V]LeadGrid Page_PreInit END.",(CrmGridTrace.Sw.TraceVerbose) ? CrmGridTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
		}

        override protected void OnInit(EventArgs e)
        {
           if ( CrmGridTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose )
               Trace2.WriteLine( "[V]LeadGrid OnInit BEG.",(CrmGridTrace.Sw.TraceVerbose) ? CrmGridTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
            InitializeComponent();
            base.OnInit(e);
           if ( CrmGridTrace.Sw.TraceVerbose || ModuleTraceSwitch.Sw.TraceVerbose )
               Trace2.WriteLine( "[V]LeadGrid OnInit END.",(CrmGridTrace.Sw.TraceVerbose) ? CrmGridTrace.Sw.Info:ModuleTraceSwitch.Sw.Info);
        }

        private void InitializeComponent()
        {
            Load                        +=      new System.EventHandler(this.Page_Load);
            RadGrid1.ColumnCreated      +=      new GridColumnCreatedEventHandler(RadGrid1_ColumnCreated);
            RadGrid1.ItemDataBound      +=      new GridItemEventHandler(RadGrid1_ItemDataBound);
            RadGrid1.NeedDataSource     +=      new GridNeedDataSourceEventHandler(RadGrid1_NeedDataSource);
            RadGrid1.ItemCommand        +=      new GridCommandEventHandler(RadGrid1_ItemCommand);
            RadGrid1.ItemCreated        +=      new GridItemEventHandler(RadGrid1_ItemCreated);
        }

       #endregion Std Overrides
        
    }
}